package com.yy.myvideoplayer

import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.SeekBar
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.yy.finvideoplayer.model.MediaDecode
import com.yy.finvideoplayer.enum.OperateType
import com.yy.finvideoplayer.manager.VideoPlayerManager
import com.yy.finvideoplayer.model.PlayerOperation
import com.yy.finvideoplayer.model.PlayerOptions
import com.yy.finvideoplayer.model.PlayerOptions.DecoderType
import com.yy.finvideoplayer.utils.JsonUtil
import com.yy.finvideoplayer.videoview.VideoControlView
import com.yy.myvideoplayer.data.VideoSrc
import com.yy.myvideoplayer.databinding.ActivityMainBinding
import kotlinx.serialization.json.Json
import java.io.InputStream

class MainActivity : AppCompatActivity()/*,VideoControlView.IPermissionRequestListener*/ {


    private val TAG = "MainActivity"

    private lateinit var binding: ActivityMainBinding
    private lateinit var videoList: List<VideoSrc>
    private var videoSrc: String = ""
    private var mediaDecode: MediaDecode? = null
    //private lateinit var permissionLauncher: ActivityResultLauncher<Array<String>>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 在onCreate中注册，这是安全的时机
        /*permissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { results ->
            Log.d("PermissionDebug", "权限请求结果: $results")
            val granted = results.values.all { it }
            // 将结果传递给 VideoControlView
            videoControlView?.getPermissionResultCallback()?.invoke(granted)
        }*/


        //初始化数据
        videoList = JsonUtil.loadListFromAssets(this, "video_src.json")
        handleVideoSelect()
        handleDecodeSelect()
        handleOperationSelect()


        binding.insertVideo.setOnClickListener{

            val insertVideoOptions = JsonUtil.loadFromAssets<PlayerOptions>(this@MainActivity, "insert.json")
            insertVideoOptions?.src = this.videoSrc
            insertVideoOptions?.decoderType = this.mediaDecode?.decoderType!!
            val jsonString = JsonUtil.toJson(insertVideoOptions)
            VideoPlayerManager.instance.insertVideoPlayer(jsonString, binding.videoViewContainer)
        }

        binding.updateVideo.setOnClickListener{
            val updateParams = JsonUtil.readJsonFileFromAssets(this@MainActivity, "update.json")
            VideoPlayerManager.instance.updateVideoPlayer(updateParams)
        }

        binding.deleteVideo.setOnClickListener{
            val deleteParams = JsonUtil.readJsonFileFromAssets(this@MainActivity, "delete.json")
            VideoPlayerManager.instance.removeVideoPlayer(deleteParams)

        }

        binding.operateVideo.setOnClickListener{

            val operation = JsonUtil.loadFromAssets<PlayerOperation>(this@MainActivity, "operation.json")
            if (operation != null) {
                operation.type = this.operateType
                VideoPlayerManager.instance.operateVideoPlayer(operation.videoPlayerId,operation)
            }
        }

        /*binding.btnControl.setOnClickListener{
            //VideoPlayerManager.showControl()
        }

        binding.btnPlay.setOnClickListener{
            val operateOption = OperateOption(type = OperateType.PLAY.value);
            val jsonString = Json.encodeToString(OperateOption.serializer(), operateOption)
            //VideoPlayerManager.operateVideoplayer(jsonString)
        }

        binding.btnStop.setOnClickListener{
            val operateOption = OperateOption(type = OperateType.STOP.value);
            val jsonString = Json.encodeToString(OperateOption.serializer(), operateOption)
            //VideoPlayerManager.operateVideoplayer(jsonString)
        }

        binding.btnPause.setOnClickListener{
            val operateOption = OperateOption(type = OperateType.PAUSE.value);
            val jsonString = Json.encodeToString(OperateOption.serializer(), operateOption)
            //VideoPlayerManager.operateVideoplayer(jsonString)
        }*/


    }

    private fun handleDecodeSelect() {
        val decodeList = listOf(
            MediaDecode("系统播放器", DecoderType.MEDIA_PLAYER),
            MediaDecode("Ijk播放器", DecoderType.IJK_PLAYER),
            MediaDecode("Exo播放器", DecoderType.EXO_PLAYER),
        )
        val videoTitles = decodeList.map { it.title }
        val adapter = ArrayAdapter(this, R.layout.list_item, videoTitles)
        binding.spDecoder.setAdapter(adapter)
        binding.spDecoder.setOnItemClickListener { _, _, position, _ ->
            val selectedDecode = decodeList[position]
            handleSelectedDecode(selectedDecode)
        }

    }

    private var operateType = "play"
    private fun handleOperationSelect() {
        val decodeList = listOf(
            "play","pause","stop","seek","send_danmu","playback_rate","request_full_screen",
            "exit_full_screen","show_status_bar","hide_status_bar","exit_picture_in_picture"
        )
        val adapter = ArrayAdapter(this, R.layout.list_item, decodeList)
        binding.spOperation.setAdapter(adapter)
        binding.spOperation.setOnItemClickListener { _, _, position, _ ->
            this.operateType = decodeList[position]
        }

    }

    private fun handleVideoSelect() {
        val videoTitles = videoList.map { it.title }
        val adapter = ArrayAdapter(this, R.layout.list_item, videoTitles)
        binding.spVideo.setAdapter(adapter)
        binding.spVideo.setOnItemClickListener { _, _, position, _ ->
            val selectedVideo = videoList[position]
            handleSelectedVideo(selectedVideo)
        }
    }


    private fun handleSelectedVideo(video: VideoSrc) {
        // 处理选中的视频
        Log.d("SelectedVideo", "ID: ${video.id}, URL: ${video.url}")
        this.videoSrc = video.url
    }

    private fun handleSelectedDecode(decode: MediaDecode) {
        // 处理选中的视频
        Log.d("SelectedDecode", "Title: ${decode.title}")
        this.mediaDecode = decode
    }


    private fun loadDanmakuJsonFromAssets(context: Context, fileName: String): String{
        return try {
            // 从assets目录读取文件
            val inputStream: InputStream = context.assets.open(fileName)
            val jsonStr = inputStream.bufferedReader().use { it.readText() }
            Log.i(TAG, "jsonStr: $jsonStr")
            jsonStr
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }


    /*private var videoControlView: VideoControlView? = null
    override fun setPermissionRequestForControllView(videoControlView: VideoControlView){
        this.videoControlView = videoControlView
    }

    override fun unSetPermissionRequestForControllView() {
        this.videoControlView = null
    }

    override fun requestStoragePermission() {

        Log.d("PermissionDebug", "权限未授予，开始请求...")
        val permissionsToRequest = arrayOf(
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE
        )
        // 检查是否应该显示解释性UI
        if (permissionsToRequest.any { permission ->
                ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
            }) {
            Log.d("PermissionDebug", "用户之前拒绝过，应考虑解释权限用途。")
            // 这里可以展示一个对话框向用户解释为什么需要这个权限:cite[3]
        } else {
            Log.d("PermissionDebug", "首次请求或用户选择了'不再询问'。")
        }

        // 发起权限请求
        permissionLauncher.launch(permissionsToRequest)


        *//*permissionLauncher.launch(
            arrayOf(
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.READ_EXTERNAL_STORAGE
            )
        )*//*
    }*/
}